package com.gec.yigou.pms.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.yigou.common.bean.PageVo;
import com.gec.yigou.common.bean.Query;
import com.gec.yigou.common.bean.QueryCondition;

import com.gec.yigou.pms.dao.CategoryDao;
import com.gec.yigou.pms.entity.CategoryEntity;
import com.gec.yigou.pms.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageVo(page);
    }

    @Override
    public List<CategoryEntity> listWhithTree() {

        //1. 查出所有分类
        List<CategoryEntity> entites = this.baseMapper.selectList(null);
        //2.组装父子的树形结构
        //2.1找到所有一级分类   一级分类父id为0    parent_cid
        List<CategoryEntity> level1Menus =entites.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .map(menu ->{   //每一级分类CategoryEntity
                    menu.setChildren(getChildrens(menu,entites)); //为一级分类找到子分类
                    return menu;
                })
                .sorted((menu1,menu2)->{  //为每一个分类对象排序  menu1 前一个对象menu2后一个对象
                    return (menu1.getSort() ==null ? 0:menu1.getSort())- (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return level1Menus;

    }

    /**
     *
     * @param root  当前菜单
     * @param all  所有菜单数据
     * @return
     * 递归查找所有菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> {
                    //当前对象父id与指定对象id相同那么 为指定对象子分类
                    return root.getCatId() == categoryEntity.getParentCid();
                })
                .map(categoryEntity -> { //每个分类下面添加子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity,all));
                    return categoryEntity;//返回当前菜单
                })
                .sorted((menu1,menu2)->{  //为每一个分类对象排序  menu1 前一个对象menu2后一个对象
                    return (menu1.getSort() ==null ? 0:menu1.getSort())- (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());//搜集所有数据

        return  children;
    }

}